"""
Analysis and data interpretation prompts for FastMCP
"""

from fastmcp import FastMCP, Context
from typing import List, Optional
from pydantic import Field


class AnalysisPrompts:
    """Analysis and data interpretation prompts for FastMCP"""

    def __init__(self, mcp: FastMCP):
        """Initialize and register analysis prompts with the FastMCP server"""
        self.mcp = mcp

    def register(self):
        """Register all analysis-related prompts"""
        self.mcp.prompt(
            name="analyze_data_trend",
            description="Generate a prompt for analyzing data trends and patterns",
            tags={"analysis", "data", "trends"},
        )(self.analyze_data_trend)

        self.mcp.prompt(
            name="performance_review",
            description="Generate a prompt for comprehensive performance analysis",
            tags={"analysis", "performance", "evaluation"},
        )(self.performance_review)

        self.mcp.prompt(
            name="comparative_analysis",
            description="Generate a prompt for systematic comparative analysis",
            tags={"analysis", "comparison", "decision-making"},
        )(self.comparative_analysis)

        self.mcp.prompt(
            name="problem_diagnosis",
            description="Generate a prompt for systematic problem diagnosis",
            tags={"analysis", "problem-solving", "diagnosis"},
        )(self.problem_diagnosis)

    def analyze_data_trend(
        self,
        data_type: str = Field(
            description="Type of data to analyze (e.g., sales, metrics, performance)"
        ),
        time_period: str = Field(
            description="Time period for analysis (e.g., monthly, quarterly, yearly)"
        ),
        focus_areas: List[str] = Field(
            description="Specific areas to focus on in the analysis"
        ),
        include_predictions: bool = Field(
            default=False, description="Whether to include future predictions"
        ),
    ) -> str:
        """Generate a prompt for data trend analysis."""

        focus_text = ", ".join(focus_areas) if focus_areas else "general patterns"
        prediction_text = (
            "\n\nAlso provide predictions for the next period based on the observed trends."
            if include_predictions
            else ""
        )

        prompt = f"""Please analyze the {time_period} {data_type} data and provide insights on the following:

1. **Overall Trends**: Identify the main trends and patterns in the data
2. **Key Metrics**: Highlight the most important metrics and their changes
3. **Focus Areas**: Pay special attention to {focus_text}
4. **Anomalies**: Point out any unusual patterns or outliers
5. **Insights**: Provide actionable insights based on the analysis

Please structure your analysis with clear headings and include specific data points to support your conclusions.{prediction_text}"""

        return prompt

    async def performance_review(
        self,
        ctx: Context,
        subject: str = Field(
            description="What is being reviewed (system, employee, process, etc.)"
        ),
        metrics: List[str] = Field(
            description="Key performance indicators to evaluate"
        ),
        time_frame: str = Field(description="Time period for the review"),
    ) -> str:
        """Generate a comprehensive performance review prompt."""

        await ctx.info(f"Creating performance review prompt for {subject}")

        # Ensure metrics is a list, not a FieldInfo object
        metrics_items = metrics if isinstance(metrics, list) else []
        metrics_list = "\n".join(f"- {metric}" for metric in metrics_items)

        prompt = f"""Conduct a comprehensive performance review for: **{subject}**

**Review Period**: {time_frame}

**Key Performance Indicators to Evaluate**:
{metrics_list}

**Analysis Framework**:

1. **Quantitative Analysis**
   - Measure current performance against each KPI
   - Compare with previous periods and established benchmarks
   - Calculate improvement or decline percentages

2. **Qualitative Assessment**
   - Assess the quality and effectiveness of performance
   - Identify strengths and areas for improvement
   - Consider external factors that may have influenced performance

3. **Root Cause Analysis**
   - Investigate underlying causes of performance issues
   - Identify successful strategies and best practices
   - Analyze resource allocation and utilization

4. **Recommendations**
   - Provide specific, actionable recommendations for improvement
   - Suggest resource reallocation or process changes
   - Set realistic goals for the next review period

5. **Implementation Plan**
   - Outline steps to implement recommendations
   - Establish timeline and milestones
   - Define success metrics for monitoring progress

Please provide a detailed analysis with supporting data and clear recommendations."""

        return prompt

    def comparative_analysis(
        self,
        items_to_compare: List[str] = Field(
            description="List of items, options, or scenarios to compare"
        ),
        comparison_criteria: List[str] = Field(
            description="Criteria or dimensions for comparison"
        ),
        decision_context: str = Field(
            description="Context or purpose of the comparison"
        ),
        weight_importance: bool = Field(
            default=True, description="Whether to weight criteria by importance"
        ),
    ) -> str:
        """Generate a prompt for systematic comparative analysis."""

        # Ensure lists are not FieldInfo objects
        items_list = items_to_compare if isinstance(items_to_compare, list) else []
        criteria_list = (
            comparison_criteria if isinstance(comparison_criteria, list) else []
        )

        items_text = "\n".join(f"{i+1}. {item}" for i, item in enumerate(items_list))
        criteria_text = "\n".join(f"- {criterion}" for criterion in criteria_list)

        weighting_instruction = (
            """
4. **Criteria Weighting**
   - Assign importance weights to each criterion (1-10 scale)
   - Justify the weighting based on the decision context
   - Calculate weighted scores for each option"""
            if weight_importance
            else ""
        )

        prompt = f"""Perform a systematic comparative analysis for the following decision context:

**Decision Context**: {decision_context}

**Options to Compare**:
{items_text}

**Comparison Criteria**:
{criteria_text}

**Analysis Structure**:

1. **Individual Assessment**
   - Evaluate each option against every criterion
   - Provide specific details and evidence for each evaluation
   - Use a consistent scoring scale (1-10) for quantitative comparison

2. **Side-by-Side Comparison**
   - Create a comparison matrix showing all options against all criteria
   - Highlight strengths and weaknesses of each option
   - Identify clear winners and losers for each criterion

3. **Trade-off Analysis**
   - Analyze the trade-offs between different options
   - Identify which option excels in which areas
   - Consider the significance of various trade-offs{weighting_instruction}

5. **Recommendation**
   - Provide a clear recommendation based on the analysis
   - Explain the reasoning behind the recommendation
   - Address potential concerns or limitations of the chosen option

6. **Alternative Scenarios**
   - Consider how the recommendation might change under different circumstances
   - Identify the second-best option and when it might be preferred

Please provide a thorough, objective analysis with clear justifications for all assessments."""

        return prompt

    def problem_diagnosis(
        self,
        problem_description: str = Field(
            description="Brief description of the problem or issue"
        ),
        affected_areas: List[str] = Field(
            description="Areas or systems affected by the problem"
        ),
        symptoms: List[str] = Field(
            description="Observable symptoms or manifestations"
        ),
        urgency_level: str = Field(
            default="medium", description="Urgency level: low, medium, high, critical"
        ),
    ) -> str:
        """Generate a systematic problem diagnosis prompt."""

        # Ensure lists are not FieldInfo objects
        areas_list = affected_areas if isinstance(affected_areas, list) else []
        symptoms_list = symptoms if isinstance(symptoms, list) else []

        affected_text = "\n".join(f"- {area}" for area in areas_list)
        symptoms_text = "\n".join(f"- {symptom}" for symptom in symptoms_list)

        # Ensure string parameters are not FieldInfo objects
        urgency = urgency_level if isinstance(urgency_level, str) else "medium"

        urgency_context = {
            "low": "This is a low-priority issue that can be addressed systematically over time.",
            "medium": "This issue requires attention and should be resolved in a reasonable timeframe.",
            "high": "This is a high-priority issue that requires prompt attention and resolution.",
            "critical": "This is a critical issue requiring immediate action and rapid resolution.",
        }.get(urgency.lower(), "Urgency level not specified.")

        prompt = f"""Conduct a systematic diagnosis of the following problem:

**Problem Description**: {problem_description}

**Urgency Level**: {urgency.title()} - {urgency_context}

**Affected Areas**:
{affected_text}

**Observed Symptoms**:
{symptoms_text}

**Diagnostic Framework**:

1. **Problem Definition**
   - Clearly define the core problem
   - Distinguish between symptoms and root causes
   - Establish the scope and boundaries of the issue

2. **Information Gathering**
   - What additional information is needed?
   - Who should be consulted or interviewed?
   - What data should be collected?

3. **Root Cause Analysis**
   - Use the "5 Whys" technique to drill down to root causes
   - Create a cause-and-effect diagram
   - Identify contributing factors and their relationships

4. **Impact Assessment**
   - Quantify the impact on different areas
   - Assess short-term and long-term consequences
   - Evaluate the cost of inaction

5. **Hypothesis Formation**
   - Develop testable hypotheses about the root cause
   - Prioritize hypotheses by likelihood and impact
   - Design tests to validate or refute each hypothesis

6. **Solution Strategy**
   - Outline potential solution approaches
   - Consider immediate fixes vs. long-term solutions
   - Assess resource requirements and feasibility

7. **Risk Assessment**
   - Identify risks associated with different solution approaches
   - Develop contingency plans
   - Consider potential side effects or unintended consequences

Please provide a thorough, structured diagnosis with actionable next steps."""

        return prompt
